import ModelBase from '..'
import { defineAsyncBindableProperty } from '../../../utils'
import { get } from '../../../utils/request'
import BookModel from '../book'

function UserModel() {}

UserModel.prototype = new ModelBase('User', {
  saveUrl: () => {
    return `/users/${this.id || 0}`
  },
})

defineAsyncBindableProperty(
  UserModel.prototype,
  'allUsers',
  async function() {
    const usersRes = await get(`/users`)
    const users = (usersRes && usersRes.data) || []
    const userModel = this
    return users.map((user) => {
      defineAsyncBindableProperty(
        user,
        'books',
        function() {
          return BookModel.getBooksByUserId(this.id)
        },
        []
      )
      return userModel.push(user)
    })
  },
  []
)

export default new UserModel()
